const fs = require('fs');
const path = require('path');

// 动态路由处理中间件
const dynamicHandler = (req, res, next) => {
  // 检查是否是 POST /vi/e6/:name/register
  if (req.method === 'POST' && req.path.startsWith('/vi/e6/')) {
    const pathParts = req.path.split('/');
    const name = pathParts[2]; // 提取 :name 参数

    const lastField = req.path.split('/').filter(part => part !== '').pop();


    // 构建配置文件路径
    const dirPath = path.join(__dirname, '../data', `${lastField}_${req.method}`);
    const configPath = path.join(dirPath, 'config.json');

    // 加载配置
    let config = [];
    config = require(configPath);

    // 匹配条件
    const matchedRule = config.find(rule => {
      if (!rule.condition) return true;
      const { status } = rule.condition;

      // 根据请求查询参数中的 status 字段匹配
      if (req.body.status !== status) return false;

      return true;
    });

    if (!matchedRule) {
      const configDefault = path.join(dirPath, 'default.json');
      console.log(`Reading file: ${configDefault}`); // 调试输出
      const responseDefault = require(configDefault);

      return res.status(parseInt(responseDefault.status)).json(responseDefault);
    }

    // 读取响应文件
    const filePath = path.join(dirPath, matchedRule.responsePath);
    console.log(`Reading file: ${filePath}`); // 调试输出

    const fileContent = fs.readFileSync(filePath, 'utf-8');
    const response = JSON.parse(fileContent);

    return res.status(parseInt(response.status)).json(response);
  }

  // 如果不匹配动态路由，继续处理其他路由
  next();
};

module.exports = dynamicHandler;